package my.jwds.p22;

import java.util.ArrayList;
import java.util.List;

public class GenerateParenthesis {
    public static void main(String[] args) {
        GenerateParenthesis obj = new GenerateParenthesis();
        System.out.println(obj.generateParenthesis(4));
        System.out.println(obj.generateParenthesis(5).size());
    }

    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<>();
        char[] chars = new char[2*n];
        generateParenthesis(res,chars,0,n,n);
        return res;

    }

    public void generateParenthesis(List<String> res,char[]chars,int index,int left,int right) {

        if (index == chars.length){
            res.add(new String(chars));
            return;
        }
        if (left > 0){
            chars[index] = '(';
            generateParenthesis(res,chars,index+1,left-1,right);
        }
        if (right > 0 && left != right){
            chars[index] = ')';
            generateParenthesis(res,chars,index+1,left,right-1);
        }


    }
}
